﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;

//正则表达式搜索模式字符串
namespace regexSearcher

{
    class RegexSearcher
    {
        private Regex regex;

        public RegexSearcher(string pattern)
        {
            // 构建正则表达式，转义特殊字符将"**"替换为".*"
            string escapedPattern = Regex.Escape(pattern).Replace("\\*", ".*");//.* 匹配任意长度的字符串
            regex = new Regex(escapedPattern, RegexOptions.Compiled);
        }

        public List<int> SearchInString(string text)
        {

            List<int> positions = new List<int>();
            
            MatchCollection matches = regex.Matches(text);
            foreach (Match match in matches)
            {
                positions.Add(match.Index);
            }
            return positions;
        }
        public void SearchInStream(string filePath)
        {
            byte[] fileBytes;
            string text = "";
            try
            {
                fileBytes = File.ReadAllBytes(filePath);
                text = Encoding.UTF8.GetString(fileBytes);
            }
            catch (Exception e)
            {
                Console.WriteLine($"Error reading file: {e.Message}");
                return;
            }
            List<int> positions = SearchInString(text);
            if (positions.Count > 0)
            {
                Console.WriteLine("使用正则表达式结果如下：");
                Console.WriteLine("模式串起始位置为：");
                foreach (int position in positions)
                {
                    Console.WriteLine(position);
                }
            }
            else
            {
                Console.WriteLine("模式串未找到。");
            }

        }
    }
}